import 'package:card_swiper/card_swiper.dart';
import 'package:eplorex/dao/group_dao.dart';
import 'package:eplorex/dao/home_feed_dao.dart';
import 'package:eplorex/models/group/group_base_info_model.dart';
import 'package:flutter/material.dart';

import '../../../models/moment/banner_model.dart';
import 'group_item_widget.dart';

class GroupDiscoveryPage extends StatefulWidget {
  const GroupDiscoveryPage({super.key});

  @override
  State<GroupDiscoveryPage> createState() => _GroupDiscoveryPageState();
}

class _GroupDiscoveryPageState extends State<GroupDiscoveryPage> {
  late Future<List<BannerModel>> _fetchBannerData;
  late Future<Iterable<GroupBaseInfoModel>?> _groupRecommends;

  @override
  void initState() {
    // todo 后面需要修改为正式的
    _fetchBannerData = HomeDao.fetchBanner();
    _groupRecommends = GroupDao.queryRecommendGroups();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("发现"),
      ),
      body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: FutureBuilder(
            future: Future.wait([_groupRecommends , _fetchBannerData] ),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting ||
                  !snapshot.hasData) {
                return const CircularProgressIndicator();
              }

              Iterable<GroupBaseInfoModel>? groupsBaseInfos = snapshot.data[0];
              List<BannerModel> banners = snapshot.data[1];
              return ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  if (index == 0) {
                    return _getSwiper(banners);
                  }
                  GroupBaseInfoModel baseInfoModel =
                      groupsBaseInfos.elementAt(index - 1);
                  return GroupItemWidget(
                    baseInfoModel.groupId!,
                    index,
                    baseInfoModel.groupName!,
                    baseInfoModel.groupAvatar!,
                    "自荐语",
                    99,
                  );
                },
                itemCount: groupsBaseInfos!.length + 1,
              );
            },
          )),
    );
  }

  Widget _getSwiper(List<BannerModel> banners) {
    var height = MediaQuery.of(context).size.width / 250.0 * 100.0;
    return Container(
      height: height,
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return Image.network(
            banners[index].url ?? " ",
            fit: BoxFit.fill,
          );
        },
        autoplay: true,
        itemCount: banners.length,
        pagination: SwiperPagination(),
        // control: SwiperControl(),
      ),
    );
  }
}
